package com.mmall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.dao.CategoryMapper;
import com.mmall.dao.ProductMapper;
import com.mmall.pojo.Category;
import com.mmall.pojo.Product;
import com.mmall.service.ICategoryService;
import com.mmall.service.IProductService;
import com.mmall.util.DateTimeUtil;
import com.mmall.util.PropertiesUtil;
import com.mmall.vo.ProductDetailVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("iProductService")
public class ProductServiceImpl implements IProductService {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private ICategoryService categoryService;
    /**
     * 新增或者修改产品service
     * @param product
     * @return
     */
    public ServerResponse productSaveOrUpdate(Product product){
        if (product!=null){
           if (StringUtils.isNotBlank(product.getSubImages())){
               String[] subImageArray=product.getSubImages().split(",");
               if (subImageArray.length>0){
                   product.setMainImage(subImageArray[0]);
               }
           }
           //修改
           if (product.getId()!=null){
              int updateRow=productMapper.updateByPrimaryKey(product);
              if (updateRow>0){
                  return ServerResponse.createBySuccessMessage("修改产品成功");
              }else{
                  return ServerResponse.createByErrorMessage("修改产品失败");
              }
           }else{//新增
               int  saveRow=productMapper.insert(product);
               if (saveRow>0){
                   return ServerResponse.createBySuccessMessage("新增产品成功");
               }else{
                   return ServerResponse.createByErrorMessage("新增产品失败");
               }
           }
        }
        return  ServerResponse.createByErrorMessage("新增或者修改产品的参数不正确");
    }

    /**
     * 修改商品的销售状态
     * @param productId
     * @param status
     * @return
     */
    public ServerResponse setSaleStatus(Integer productId,Integer status){
        if (productId==null||status==null){
            return  ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        Product product=new Product();
        product.setId(productId);
        product.setStatus(status);
        int resultRow=productMapper.updateByPrimaryKeySelective(product);
        if (resultRow>0){
            return  ServerResponse.createBySuccessMessage("商品销售状态修改成功");
        }
        return ServerResponse.createByErrorMessage("商品销售状态修改失败");
    }

    /**
     * 查询商品的详情
     * @param productId
     * @return
     */
    public ServerResponse getProductDetail(Integer productId){
       if (productId==null){
           return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc());
       }
       Product product=productMapper.selectByPrimaryKey(productId);
       if (product==null){
           return ServerResponse.createByErrorMessage("商品已经下架或者删除");
       }
        ProductDetailVo  productDetailVo=assembelProductDetailVo(product);
       return  ServerResponse.createBySuccess(productDetailVo);
    }

    public ProductDetailVo assembelProductDetailVo(Product product){
        ProductDetailVo productDetailVo=new ProductDetailVo();
        productDetailVo.setId(product.getId());
        productDetailVo.setName(product.getName());
        productDetailVo.setSubtitle(product.getSubtitle());
        productDetailVo.setDetail(product.getDetail());
        productDetailVo.setPrice(product.getPrice());
        productDetailVo.setStatus(product.getStatus());
        productDetailVo.setStock(product.getStock());
        productDetailVo.setMainImage(product.getMainImage());
        productDetailVo.setSubImages(product.getSubImages());
        productDetailVo.setCategoryId(product.getCategoryId());

        productDetailVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix","http://img.happymmall.com/"));
        Category category=categoryMapper.selectByPrimaryKey(product.getCategoryId());
        if (category==null){
            productDetailVo.setParentCategoryId(0);//默认根节点
        }else{
            productDetailVo.setParentCategoryId(category.getParentId());
        }
        //对时间进行格式处理
        productDetailVo.setCreateTime(DateTimeUtil.dateToStr(product.getCreateTime()));
        productDetailVo.setUpdateTime(DateTimeUtil.dateToStr(product.getUpdateTime()));
        return productDetailVo;

    }

    /**
     * 查询商品的列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    public ServerResponse<PageInfo> getProductList(int pageNum,int pageSize){
        //startPage--start
        PageHelper.startPage(pageNum,pageSize);
        //填充自己的sql查询逻辑
        List<Product> productList=productMapper.selectProductList();
        List<ProductDetailVo> productDetailVoList= Lists.newArrayList();
        for (Product product:productList){
            ProductDetailVo productDetailVo=assembelProductDetailVo(product);
            productDetailVoList.add(productDetailVo);
        }
        //pageHelper-收尾
        PageInfo pageInfo=new PageInfo(productList);
        pageInfo.setList(productDetailVoList);
        return  ServerResponse.createBySuccess(pageInfo);
    }

    /**
     * 根据商品的名字/Id查询商品的列表
     * @param pageNum
     * @param pageSize
     * @param productName
     * @param productId
     * @return
     */
    public  ServerResponse<PageInfo> searchProduct(int pageNum,int pageSize,String productName,Integer productId){
        PageHelper.startPage(pageNum,pageSize);
        if (StringUtils.isNotBlank(productName)){
            productName=new StringBuilder().append("%").append(productName).append("%").toString();
        }
        List<Product> productList=productMapper.getProductByNameAndId(productName,productId);
        List<ProductDetailVo> productDetailVoList=Lists.newArrayList();
        for (Product product:productList){
            ProductDetailVo productDetailVo=assembelProductDetailVo(product);
            productDetailVoList.add(productDetailVo);
        }
        PageInfo pageInfo=new PageInfo(productList);
        pageInfo.setList(productDetailVoList);
        return ServerResponse.createBySuccess(pageInfo);
    }


    //前台商品service

    /**
     * 前台查询商品详情
     * @param productId
     * @return
     */
    public ServerResponse<ProductDetailVo> getDetail(Integer productId){
        if (productId==null){
            return  ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        Product product=productMapper.selectByPrimaryKey(productId);
        if (product==null){
            return ServerResponse.createByErrorMessage("商品已经下架或者删除");
        }
        if (product.getStatus()!= Const.ProductStatusEnum.ON_SALE.getCode()){
            return ServerResponse.createByErrorMessage("商品已经下架或者删除");
        }
        ProductDetailVo productDetailVo=assembelProductDetailVo(product);
        return ServerResponse.createBySuccess(productDetailVo);
    }

    /**
     * 前台商品的查询以及排序处理
     * @param keyword
     * @param categoryId
     * @param pageNum
     * @param pageSize
     * @param orderBy
     * @return
     */
    public ServerResponse<PageInfo>  getProductByKeywordCategory(String keyword,Integer categoryId,int pageNum,int pageSize,String orderBy){
        if (StringUtils.isBlank(keyword)&&categoryId==null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        List<Integer> cateGoryList=new ArrayList<Integer>();
        if (categoryId!=null){
            Category category=categoryMapper.selectByPrimaryKey(categoryId);
            if (category==null&&StringUtils.isBlank(keyword)){//此时不要报错，直接返回一个空
                PageHelper.startPage(pageNum,pageSize);
                List<ProductDetailVo> productListVoList = Lists.newArrayList();
                PageInfo pageInfo = new PageInfo(productListVoList);
                return ServerResponse.createBySuccess(pageInfo);
            }
            cateGoryList=categoryService.getDeepChildCategory(category.getId()).getData();
        }
        if (StringUtils.isNotBlank(keyword)){
            keyword=new StringBuilder().append("%").append(keyword).append("%").toString();
        }
        PageHelper.startPage(pageNum,pageSize);
        //排序处理
        if (StringUtils.isNotBlank(orderBy)){
            if (Const.ProductListOrderBy.PRICE_ASC_DESC.contains(orderBy)){
                String[] orderByArray=orderBy.split("_");
                PageHelper.orderBy(orderByArray[0]+" "+orderByArray[1]);
            }
        }
        List<Product> productList=productMapper.selectByNameAndCategoryIds(
                StringUtils.isBlank(keyword)?null:keyword,cateGoryList.size()==0?null:cateGoryList
        );
        List<ProductDetailVo> productDetailVoList=Lists.newArrayList();
        for (Product product:productList){
            ProductDetailVo productDetailVo=assembelProductDetailVo(product);
            productDetailVoList.add(productDetailVo);
        }
        PageInfo pageInfo=new PageInfo(productList);
        pageInfo.setList(productDetailVoList);
        return ServerResponse.createBySuccess(pageInfo);
    }
}
